package 数据结构和算法.剑指offer.矩阵.顺时针打印矩阵;

/**
 * 顺时针打印矩阵
 * <p>
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字
 * <p>
 * 分别从左向右，从上到下，从右到左，从下到上四个顺序逐次将数组加到新的数组之中
 */
public class Test {
    public int[] spiralOrder(int[][] matrix) {
        int l = 0;
        int r = matrix[0].length - 1;
        int u = 0;
        int b = matrix.length - 1;
        int x = 0;
        int[] res = new int[matrix.length * matrix[0].length];
        while (true) {
            for (int i = l; i <= r; ++i) {
                res[x++] = matrix[u][i];
            }
            if (++u > b) {
                break;
            }

            for (int i = u; u <= b; ++u) {
                res[x++] = matrix[i][l];
            }
            if (l > --r) {
                break;
            }

            for (int i = r; i >= l; --i) {
                res[x++] = matrix[b][i];
            }
            if (u > --b) {
                break;
            }

            for (int i = b; i >= u; ++i) {
                res[x++] = matrix[i][l];
            }
            if (++l > r) {
                break;
            }
        }

        return res;
    }
}
